import { TagSelect } from '@/components/index.jsx';
import { useEffect, useState } from 'react';
import { PermissionApi } from '@/api/permission/api.js';
import { MAX_LIMIT } from '@/constants/pageConstant.js';
import { Spin } from 'antd';

/**
 * 权限选择器
 * @param props 属性
 * @param props.id 组件id
 * @param props.value 初始值
 * @param props.onChange 选择变化回调
 */
export default function PermissionSelect(props) {
  const { id, onChange, value } = props;
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    onPageLoad();
  }, []);

  function onPageLoad() {
    setLoading(true);
    // 获取权限列表
    PermissionApi.getList(1, MAX_LIMIT, {
      status: '1'
    }).then(({ code, data }) => {
      if (code === 0) {
        const { list } = data;
        setOptions(
          list.map((permission) => ({
            label: permission?.permissionName,
            value: permission?.permissionCode,
            tooltip: permission?.permissionDesc
          }))
        );
      }
      setLoading(false);
    });
  }

  return (
    <Spin spinning={loading}>
      <TagSelect
        id={id}
        options={options}
        values={value}
        onChange={(list) => {
          if (onChange) {
            onChange(list);
          }
        }}
      />
    </Spin>
  );
}
